package com.shuqi.activity;

import java.util.List;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.SqImageManager;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.OfferWallItemController;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.OfferWallInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 推广墙详情界面
 * 
 * @author linyuren
 * 
 */
public class OfferWallItemActivity extends ActivityBase implements HttpRequestErrListener,
        IEventListener, OnClickListener {

    private final static int init = EventTypeConstants.BASE;
    private final static int initAppDataSuccess = init + 1;
    private final static int show404 = init + 2;
    private OfferWallItemController controller;

    /** 进度圈 */
    private LinearLayout layout;
    /** 无网络提示 */
    private View act_nonetwork;
    private CommonTitle mTitle;

    private OfferWallInfo info;
    private String from = "2"; // 拼接URL
    private String itemid; // 传递过来的应用id
    private String packagename;// 传递过来的应用名称

    ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case initAppDataSuccess:
                    activityInitData();
                    break;
                case show404:
                    layout.setVisibility(View.GONE);
                    act_nonetwork.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.controller =
                (OfferWallItemController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_OFFERWALL_ITEM_ACTIVITY, this);
        this.controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.act_offerwall_item_view);
        handler.sendEmptyMessage(init);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        if (!Util.isNetworkConnected(OfferWallItemActivity.this)) {
                            return;
                        }
                        layout.setVisibility(View.VISIBLE);
                        controller.handle(0, itemid, from); // 获取应用详情数据
                    }
                });

                break;
        }
    }

    @Override
    public void activityLogicForward() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);

        this.layout = (LinearLayout) findViewById(R.id.include_loading);
        this.act_nonetwork = (View) findViewById(R.id.include_error);
        this.act_nonetwork.findViewById(R.id.retry).setOnClickListener(this);

        if ("app".equals(getIntent().getStringExtra("from"))) {
            this.from = "2";
        } else if ("game".equals(getIntent().getStringExtra("from"))) {
            this.from = "3";
        } else {
            from = "2";
        }
        // 接收参数
        this.itemid = getIntent().getStringExtra("itemid");
        this.packagename = getIntent().getStringExtra("packagename");
        String channel = getIntent().getStringExtra("channel");
        from = channel;
        this.setDownLoadButListener();
        this.controller.handle(0, this.itemid, this.from); // 获取应用详情数据
        this.layout.setVisibility(View.VISIBLE);
    }

    /** 下载按钮监听事件 */
    private void setDownLoadButListener() {
        // 下载安装按钮监听事件
        this.findViewById(R.id.tv_offerwallitem_download).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if ("有 更 新".equals(((TextView) v).getText())) {
                    if (info != null && info.getDownloadUrl() != null
                            && info.getDownloadUrl().startsWith("http")) {
                        // Url后拼接site=2表示第二个页面，update=1表示更新下载
                        try {
                            Intent web =
                                    new Intent(Intent.ACTION_VIEW, Uri.parse(info.getDownloadUrl()
                                            + "&site=2&update=1&sd=" + from));
                            startActivity(web);
                        } catch (Exception e) {
                            // TODO 异常
                        }

                    }
                } else if ("下 载 安 装".equals(((TextView) v).getText())) {
                    if (info != null && info.getDownloadUrl() != null
                            && info.getDownloadUrl().startsWith("http")) {
                        // Url后拼接site=2表示第二个页面，update=0表示直接下载
                        try {
                            Intent web =
                                    new Intent(Intent.ACTION_VIEW, Uri.parse(info.getDownloadUrl()
                                            + "&site=2&update=0&sd=" + from));
                            startActivity(web);
                        } catch (Exception e) {
                            // TODO 异常
                        }
                    }
                } else {
                    PackageInfo pi = null;
                    try {
                        pi = getPackageManager().getPackageInfo(packagename, 0);
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (pi != null) {
                        Intent intent =
                                getPackageManager().getLaunchIntentForPackage(pi.packageName);
                        ComponentName cn = intent.getComponent();
                        intent = new Intent(Intent.ACTION_MAIN);
                        intent.setComponent(cn);
                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                List<OfferWallInfo> list = (List<OfferWallInfo>) data;
                if (list != null && list.size() > 0) {
                    this.info = list.get(0);
                } else {
                    this.info = null;
                }
                this.handler.sendEmptyMessage(initAppDataSuccess);
                break;
            default:
                this.handler.sendEmptyMessage(show404);
                break;
        }
    }

    @Override
    public void activityInitData() {
        if (this.info != null) {
            // 加载ICON图
            loadHeaderImage(info.getIconUrl(), R.id.iv_offerwallitem);
            // 简介图
            if (info.getImgUrls().size() > 0) {
                loadHeaderImage(info.getImgUrls().get(0), R.id.iv_offerwallitem_brief1);
            } else {
                findViewById(R.id.scroll_offerwallitem).setVisibility(View.GONE);
            }
            if (info.getImgUrls().size() > 1) {
                loadHeaderImage(info.getImgUrls().get(1), R.id.iv_offerwallitem_brief2);
            } else {
                findViewById(R.id.iv_offerwallitem_brief2).setVisibility(View.GONE);
            }
            if (info.getImgUrls().size() > 2) {
                loadHeaderImage(info.getImgUrls().get(2), R.id.iv_offerwallitem_brief3);
            } else {
                findViewById(R.id.iv_offerwallitem_brief3).setVisibility(View.GONE);
            }
            // 软件名
            ((TextView) findViewById(R.id.tv_offerwallitem_name)).setText(info.getName());
            // 版本
            ((TextView) findViewById(R.id.tv_offerwallitem_versionname)).setText("版本 : "
                    + info.getVersionName());
            // 大小
            ((TextView) findViewById(R.id.tv_offerwallitem_size)).setText("大小 : " + info.getSize());
            // 人气
            float groom;
            try {
                groom = Float.parseFloat(info.getGroom());
            } catch (Exception e) {
                e.printStackTrace();
                groom = 0;
            }
            ((RatingBar) findViewById(R.id.rb_offerwallitem_groom)).setRating(groom);
            // 更新时间
            ((TextView) findViewById(R.id.tv_offerwallitem_update)).setText("更新时间 : "
                    + info.getUpdateTime());
            // 支持系统
            ((TextView) findViewById(R.id.tv_offerwallitem_system)).setText("支持系统 : "
                    + info.getSystem());
            // 简介
            String brief = info.getBrief();
            if (!TextUtils.isEmpty(brief)) {
                brief = brief.replaceAll("\\[br\\]", "\n");
            }
            ((TextView) findViewById(R.id.tv_offerwallitem_brief)).setText(brief);
            // 下载安装按钮
            TextView btn = (TextView) findViewById(R.id.tv_offerwallitem_download);
            PackageInfo pi = null;
            try {
                pi = getPackageManager().getPackageInfo(this.packagename, 0);
            } catch (NameNotFoundException e) {
            }
            if (pi != null) {
                Intent intent = getPackageManager().getLaunchIntentForPackage(pi.packageName);
                if (intent != null) {
                    try {
                        int versionCode = Integer.valueOf(info.getVersionCode());
                        if (versionCode > pi.versionCode) {
                            btn.setText("有 更 新");
                        } else {
                            btn.setText("已 安 装");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    btn.setText("下 载 安 装");
                }
            } else {
                btn.setText("下 载 安 装");
            }
        }
        this.layout.setVisibility(View.GONE);
        act_nonetwork.setVisibility(View.GONE);
    }

    /**
     * 异步加载头像图片
     */
    private void loadHeaderImage(String imgUrl, int id) {
        if (imgUrl != null && !imgUrl.equals("") && info != null) {
            final ImageView imageView = (ImageView) findViewById(id);
            SqImageManager.getImageManager().displayImage(imgUrl, imageView,
                    SqImageManager.IMG_DEFAULT, R.drawable.icon_def_bookimg_list);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        ActivityManager.getInstance().finishActivity(this);
        super.onDestroy();
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
